import { component$ } from '@builder.io/qwik';
import { type DocumentHead, routeLoader$, routeAction$, Form, zod$ } from '@builder.io/qwik-city';
import Button from '~/components/ui/Button';
import Input from '~/components/ui/Input';
import Card, { CardBody, CardTitle } from '~/components/ui/Card';
import { checkAuth } from '~/server/authn';
import { z } from 'zod';
import { db } from '~/server/db';
import { pw } from '~/server/pw';
import _ from 'lodash';
import { userAccountService } from '~/server/service/user-account-service';
import { userPasswordService } from '~/server/service/user-password-service';
import { userInfoService } from '~/server/service/user-info-service';

export const useLoader = routeLoader$(async (requestEvent) => {
  const auth = await checkAuth(requestEvent);
  if (auth.ok) {
    throw requestEvent.redirect(307, '/me');
  }
});

export const useRegisterAction = routeAction$(
  async (props, requestEvent) => {
    const auth = await checkAuth(requestEvent);
    if (auth.ok) {
      throw requestEvent.redirect(307, '/me');
    }

    const { phone, password } = props;

    return db.$transaction(async (tx) => {
      const userAccount = await userAccountService.findByPhone(tx, phone);
      if (userAccount) {
        return requestEvent.error(400, '手机号已经被注册。');
      }

      const user = await userAccountService.create(tx, { phone });

      const encodedPassword = await pw.encode(password);

      await Promise.all([
        userPasswordService.create(tx, {
          userId: user.userId,
          encryptedPassword: encodedPassword,
        }),
        userInfoService.create(tx, {
          userId: user.userId,
          nickname: '', // TODO: 应指定默认值
          avatar: '',
          description: '',
        }),
      ]);

      return requestEvent.json(201, '');
    });
  },
  zod$(
    z.object({
      phone: z.string().regex(/^1[3-9]\d{9}$/, { message: '手机号格式错误。' }),
      password: z
        .string()
        .min(10, { message: '密码至少应该包含 10 个字符。' })
        .max(36, { message: '密码不可超过 36 个字符' }),
    })
  )
);

function ErrorMessage({ message }: { message: string | null | undefined }) {
  if (!message) return null;
  return <div class="text-red-500 text-sm font-bold">{message}</div>;
}

export default component$(() => {
  const registerAction = useRegisterAction();

  const fieldErrors = registerAction.value?.fieldErrors;
  const phoneErrors = fieldErrors?.phone || [];
  const passwordErrors = fieldErrors?.password || [];

  // TODO: 成功后弹窗提示

  return (
    <div style={{ maxWidth: 360 }} class="mx-auto mt-40">
      <Card>
        <CardTitle>注册账户</CardTitle>
        <CardBody class="py-4">
          <Form action={registerAction}>
            <div>
              <Input name="phone" placeholder="请填写手机号" block class="my-4" />
              <ErrorMessage message={_.first(phoneErrors)} />
            </div>
            <div>
              <Input name="password" type="password" placeholder="请填写密码" block class="my-4" />
              <ErrorMessage message={_.first(passwordErrors)} />
            </div>
            <ErrorMessage message={registerAction.value?.message} />
            <div>
              <Button type="submit" varient="primary" block class="my-4">
                注册
              </Button>
            </div>
          </Form>
        </CardBody>
      </Card>
    </div>
  );
});

export const head: DocumentHead = {
  title: '注册账户',
};
